"use client";

import { TrendingUp } from "lucide-react";
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";

import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";

const chartConfig = {
  reward: {
    label: "Reward",
    color: "var(--chart-1)",
  },
} satisfies ChartConfig;

export function ChartLineLinear({
  sseData,
}: {
  sseData: { reward: number }[];
}) {
  // 保证至少有两个点
  const data =
    sseData.length === 1
      ? [
          { index: 0, reward: sseData[0].reward },
          { index: 1, reward: sseData[0].reward },
        ]
      : sseData.map((item, index) => ({
          index,
          reward: item.reward,
        }));

  const totalReward = sseData.reduce((acc, item) => acc + item.reward, 0);
  const averageReward = totalReward / (sseData.length || 1);

  return (
    <Card className="flex-1">
      <CardHeader>
        <CardTitle>奖励函数</CardTitle>
      </CardHeader>
      <CardContent>
        <ChartContainer
          config={chartConfig}
          className="h-[calc(100vh-36rem)] w-full"
        >
          <LineChart data={data}>
            <CartesianGrid vertical={false} strokeDasharray="3 3" />
            <XAxis
              dataKey="index"
              tickLine={false}
              axisLine={false}
              tickMargin={8}
            />
            <YAxis tickLine={false} axisLine={false} tickMargin={8} />
            <ChartTooltip
              cursor={false}
              content={<ChartTooltipContent hideLabel />}
            />
            <Line
              dataKey="reward"
              type="linear"
              stroke="hsl(var(--chart-1))"
              strokeWidth={2}
              dot={sseData.length <= 1}
              isAnimationActive={true}
              animationDuration={200}
            />
          </LineChart>
        </ChartContainer>
      </CardContent>
      <CardFooter className="flex-col items-start gap-2 text-sm">
        <div className="flex gap-2 leading-none font-medium">
          累计奖励值 {totalReward.toFixed(4)} <TrendingUp className="h-4 w-4" />
        </div>
        <div className="text-muted-foreground leading-none">
          平均奖励 {averageReward.toFixed(4)}
        </div>
      </CardFooter>
    </Card>
  );
}
